package com.banciyuan.bcywebview.biz.privatemessage;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.MessageApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.tag.FlowView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.daoexample.model.PrivateMessage;

/**
 * Created by squall on 2016/9/9.
 */
public class EditPrivateMessageActivity extends BaseActivity implements View.OnClickListener {

    private EditText et_content;
    private ImageView iv_cancel;
    private TextView tv_send;
    private ImageView tv_emoji;
    private FlowView emoji_container;

    private PrivateMessage message;
    private String type;

    private RequestQueue queue;
    private boolean is_send;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_message);
        initArgs();
        initUi();
        initAction();
        initEmoji();
    }

    @Override
    protected void initArgs() {
        message = (PrivateMessage) getIntent().getSerializableExtra(gotoUtil.INTENT_VALUE_ONE);
        type = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_TWO);
        queue = VolleyQueue.getRquest(this);
    }

    @Override
    protected void initUi() {
        et_content = (EditText) findViewById(R.id.et_comment);
        iv_cancel = (ImageView) findViewById(R.id.iv_cancle);
        tv_send = (TextView) findViewById(R.id.tv_finish);
        tv_emoji = (ImageView) findViewById(R.id.comment_emoji);
        emoji_container = (FlowView) findViewById(R.id.emoji_container);
        et_content.setHint(String.format(getString(R.string.send_privateMessage), message.getUname()));
    }

    @Override
    protected void initAction() {
        iv_cancel.setOnClickListener(this);
        tv_send.setOnClickListener(this);
        tv_emoji.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_cancle:
                close();
                break;
            case R.id.tv_finish:
                if (vail()) {
                    postMessage();
                }
                break;
            case R.id.comment_emoji:
                if (emoji_container.getVisibility() == View.GONE) {
                    emoji_container.setVisibility(View.VISIBLE);
                    hideSoftKeyboard();
                    tv_emoji.setSelected(false);
                } else {
                    emoji_container.setVisibility(View.GONE);
                    showSoftInput(et_content);
                    tv_emoji.setSelected(true);
                }
                break;
        }
    }

    private boolean vail() {
        if (is_send) return false;
        if (TextUtils.isEmpty(et_content.getText().toString().trim())) {
            MyToast.show(this, getString(R.string.message_canot_be_null));
            return false;
        } else {
            return true;
        }
    }

    private void postMessage() {
        is_send = true;
        String url = HttpUtils.BASE_URL;
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        pairs.add(new BcyPair("content", et_content.getText().toString()));
        pairs.add(new BcyPair("to_uid", message.getUid()));
        if (StringUtil.notNullEqual(type, "new")) {
            url += MessageApi.getMessageNewMessage();
        } else if (StringUtil.notNullEqual(type, "reply")) {
            url += MessageApi.getMessageReplyMessage();
            pairs.add(new BcyPair("message_id", message.getSource_message_id()));
        }
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                is_send = false;
                try {
                    if (StatusCodeUtils.dealStatusCode(response, EditPrivateMessageActivity.this)) {
                        if (StringUtil.notNullEqual(type, "reply")) {
                            Intent intent = new Intent();
                            JSONObject jsonObject = new JSONObject(response);
                            Gson gson = new Gson();
                            PrivateMessage privateMessage = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), PrivateMessage.class);
                            intent.putExtra("privatemessage", privateMessage);
                            setResult(RESULT_OK, intent);
                            close();
                        } else {
                            MyToast.show(EditPrivateMessageActivity.this, getString(R.string.done_success));
                            close();
                        }
                    }
                } catch (Exception e) {
                    MyToast.show(EditPrivateMessageActivity.this, getString(R.string.operation_fail));
                    close();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        };
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(requestParam);
    }

    private void initEmoji() {
        String[] emojis = getResources().getStringArray(R.array.emoji);
        LayoutInflater inflater = LayoutInflater.from(EditPrivateMessageActivity.this);
        for (int i = 0; i < emojis.length; i++) {
            final TextView single_emoji = (TextView) inflater.inflate(R.layout.emoji, null);
            single_emoji.setText(emojis[i]);
            single_emoji.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String text = ((TextView) view).getText().toString();
                    et_content.setText(et_content.getText().toString() + text);
                    et_content.setSelection(et_content.getText().length());
                    emoji_container.setVisibility(View.GONE);
                    showSoftInput(et_content);
                }
            });
            emoji_container.addView(single_emoji);
        }
    }

    private void showSoftInput(final EditText et) {
        et.requestFocus();
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(et, 0);
            }
        }, 200);
    }

    public void hideSoftKeyboard() {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (null != inputManager && inputManager.isActive()) {
            inputManager.hideSoftInputFromWindow(et_content.getApplicationWindowToken(), 0);
        }
    }

    private void close() {
        finish();
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        close();
    }
}
